package com.cckj.common.exception;

import com.cckj.common.response.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
  * @Description //TODO  全局controller异常处理，validator，assert,自定义异常，运行时异常
  * @Author wjq
  * @time: 2020/11/2 14:27
  */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // Validation 实体类验证
    @ExceptionHandler(value = BindException.class)
    public ResultData bindExceptionHandler(BindException e, HttpServletRequest request){
        BindingResult bindingResult = e.getBindingResult();

        StringBuffer logSB = new StringBuffer("[method: ");
        logSB.append(request.getMethod())
             .append("] [路径：")
             .append(request.getContextPath())
             .append(request.getRequestURI())
             .append("] 参数错误:[")
             .append(bindingResult.getTarget().getClass().getName())
             .append(" { ");

        // 获取所有的校验错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            logSB.append(fieldError.getField())
                 .append(":")
                 .append(fieldError.getDefaultMessage())
                 .append("; ");
        }
        logSB.append("}]");
        log.warn(logSB.toString());

        // 获取到第一个校验错误信息
        FieldError fieldError = bindingResult.getFieldError();
        return ResultData.error(fieldError.getDefaultMessage());
    }

    // Validation 参数验证
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultData constraintViolationExceptionHandler(ConstraintViolationException e) {
        return ResultData.error(e.getConstraintViolations().iterator().next().getMessage());
    }

    // Assert 断言异常
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResultData illegalArgumentExceptionHandler(IllegalArgumentException e){
        e.printStackTrace();
        return ResultData.error(e.getMessage());
    }

    // 自定义异常
    @ExceptionHandler(value = BusinessException.class)
    public ResultData businessExceptionHandler(BusinessException e) {
        e.printStackTrace();
        // 加入日志
        return ResultData.error(e.getMessage());
    }

    // 运行时异常统一处理
    @ExceptionHandler(value = RuntimeException.class)
    public ResultData runtimeExceptionHandler(RuntimeException e) {
        e.printStackTrace();
        // 加入日志
        return ResultData.error(ResultData.ERROR_MSG);
    }


}
